// 统一导航栏管理系统
class UnifiedNavigation {
    constructor() {
        this.currentPage = this.getCurrentPage();
        this.isAuthenticated = this.checkAuthStatus();
        // 延迟初始化，等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.init());
        } else {
            this.init();
        }
    }

    // 检查认证状态
    checkAuthStatus() {
        const token = localStorage.getItem('authToken');
        return !!token;
    }

    // 获取当前页面信息
    getCurrentPage() {
        const path = window.location.pathname;
        const pageMap = {
            'dashboard.html': { name: '仪表盘', icon: 'fas fa-tachometer-alt', requiresAuth: true },
            'reports.html': { name: '访客统计', icon: 'fas fa-chart-line', requiresAuth: true },
            'blog.html': { name: '博客管理', icon: 'fas fa-blog', requiresAuth: true },
            'products.html': { name: '产品管理', icon: 'fas fa-box', requiresAuth: true },
            'orders.html': { name: '订单管理', icon: 'fas fa-shopping-cart', requiresAuth: true },
            'logs.html': { name: '网站日志', icon: 'fas fa-file-alt', requiresAuth: true },
            'system-settings.html': { name: '系统设置', icon: 'fas fa-cog', requiresAuth: true },
            'messages.html': { name: '消息中心', icon: 'fas fa-comments', requiresAuth: true },
            'category-manager.html': { name: '分类管理', icon: 'fas fa-tags', requiresAuth: true },
            'login.html': { name: '登录', icon: 'fas fa-sign-in-alt', requiresAuth: false },
            'index.html': { name: '首页', icon: 'fas fa-home', requiresAuth: false }
        };

        const fileName = path.split('/').pop();
        return pageMap[fileName] || { name: '后台管理', icon: 'fas fa-cog', requiresAuth: true };
    }

    // 初始化导航栏
    init() {
        // 如果是登录页且已登录，跳转到仪表盘
        if (this.currentPage.name === '登录' && this.isAuthenticated) {
            window.location.href = 'dashboard.html';
            return;
        }

        // 检查认证状态，如果需要认证但未登录则显示登录提示而不是跳转
        if (this.currentPage.requiresAuth && !this.isAuthenticated) {
            // 显示登录提示而不是跳转，让用户可以选择登录
            this.showLoginPrompt();
            return;
        }

        // 创建导航栏
        this.createNavigation();
        this.setupEventListeners();
        this.updateUserInfo();
    }

    // 显示登录提示
    showLoginPrompt() {
        // 创建导航栏但显示登录提示
        this.createNavigation();
        this.setupEventListeners();
        
        // 显示登录提示
        const navRight = document.querySelector('.nav-right');
        if (navRight) {
            navRight.innerHTML = `
                <div class="user-info">
                    <span style="color: #e74c3c; font-weight: 500;">请登录以访问此页面</span>
                    <button class="nav-btn login-btn" onclick="unifiedNav.navigateToLogin()">
                        <i class="fas fa-sign-in-alt"></i> 立即登录
                    </button>
                </div>
            `;
        }
    }

    // 导航到登录页
    navigateToLogin() {
        window.location.href = 'login.html';
    }

    // 创建导航栏HTML
    createNavigation() {
        const navHTML = `
            <nav class="unified-navbar">
                <div class="nav-container">
                    <!-- 左侧品牌和菜单 -->
                    <div class="nav-left">
                        <a href="dashboard.html" class="nav-brand">
                            <i class="fas fa-cog"></i>
                            <span>后台管理系统</span>
                        </a>
                        
                        <div class="nav-menu">
                            <a href="dashboard.html" class="nav-item ${this.currentPage.name === '仪表盘' ? 'active' : ''}">
                                <i class="fas fa-tachometer-alt"></i>
                                <span>仪表盘</span>
                            </a>
                            <a href="products.html" class="nav-item ${this.currentPage.name === '产品管理' ? 'active' : ''}">
                                <i class="fas fa-box"></i>
                                <span>产品管理</span>
                            </a>
                            <a href="orders.html" class="nav-item ${this.currentPage.name === '订单管理' ? 'active' : ''}">
                                <i class="fas fa-shopping-cart"></i>
                                <span>订单管理</span>
                            </a>

                        </div>
                    </div>

                    <!-- 右侧用户信息 -->
                    <div class="nav-right">
                        <div class="user-info">
                            <span id="navUsername">未登录</span>
                            <div class="user-actions">
                                <button class="nav-btn login-btn" onclick="unifiedNav.showLogin()" style="${this.isAuthenticated ? 'display:none' : ''}">
                                    <i class="fas fa-sign-in-alt"></i> 登录
                                </button>
                                <button class="nav-btn logout-btn" onclick="unifiedNav.logout()" style="${!this.isAuthenticated ? 'display:none' : ''}">
                                    <i class="fas fa-sign-out-alt"></i> 退出
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </nav>
        `;

        // 插入导航栏到页面顶部
        // 首先检查是否有导航栏容器
        const navbarContainer = document.getElementById('navbar-container');
        if (navbarContainer) {
            navbarContainer.innerHTML = navHTML;
        } else {
            // 如果没有容器，直接插入到body开头
            document.body.insertAdjacentHTML('afterbegin', navHTML);
        }
    }

    // 设置事件监听器
    setupEventListeners() {
        // 导航链接点击事件
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const href = item.getAttribute('href');
                this.navigateTo(href);
            });
        });
    }

    // 导航到指定页面
    navigateTo(page) {
        if (this.currentPage.requiresAuth && !this.isAuthenticated) {
            this.showLogin();
            return;
        }
        window.location.href = page;
    }

    // 显示登录模态框
    showLogin() {
        window.location.href = 'login.html';
    }

    // 退出登录
    logout() {
        localStorage.removeItem('authToken');
        localStorage.removeItem('userInfo');
        window.location.href = 'login.html';
    }

    // 更新用户信息
    updateUserInfo() {
        if (this.isAuthenticated) {
            const userInfo = localStorage.getItem('userInfo');
            if (userInfo) {
                try {
                    const user = JSON.parse(userInfo);
                    const usernameElement = document.getElementById('navUsername');
                    if (usernameElement) {
                        usernameElement.textContent = user.username || '管理员';
                    }
                } catch (error) {
                    console.error('解析用户信息失败:', error);
                }
            }
        }
    }

    // 检查系统状态（连接真实数据库）
    async checkSystemStatus() {
        try {
            const response = await fetch('/api/health');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            
            // 更新状态显示
            const statusElements = {
                'backendStatus': data.status === 'healthy' ? '✓ 运行正常' : '✗ 服务异常',
                'databaseStatus': data.database === 'connected' ? '✓ 已连接' : '✗ 连接失败',
                'redisStatus': data.redis === 'connected' ? '✓ 已连接' : '✗ 连接失败'
            };

            Object.keys(statusElements).forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    const status = statusElements[id];
                    const isSuccess = status.startsWith('✓');
                    element.innerHTML = `<span class="${isSuccess ? 'status-success' : 'status-error'}">${status}</span>`;
                }
            });
            
            // 记录连接状态
            console.log('系统状态检查完成:', data);
            
        } catch (error) {
            console.error('检查系统状态失败:', error);
            
            // 显示错误状态
            const statusElements = {
                'backendStatus': '✗ 连接失败',
                'databaseStatus': '✗ 连接失败',
                'redisStatus': '✗ 连接失败'
            };

            Object.keys(statusElements).forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    element.innerHTML = `<span class="status-error">${statusElements[id]}</span>`;
                }
            });
        }
    }
}

// 创建全局实例
const unifiedNav = new UnifiedNavigation();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 如果页面有系统状态显示，检查系统状态
    if (document.getElementById('backendStatus')) {
        unifiedNav.checkSystemStatus();
    }
});